package com.smartwebx.fr.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.MalformedURLException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.google.common.collect.Maps;
import com.smartwebx.fr.bean.ImgPath;
import com.smartwebx.fr.util.PathUtil;

@Controller
@RequestMapping("/file")
public class FileUploadController {
	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public @ResponseBody
	Map<String, String> uploadFileHandler(HttpServletRequest request,
			@RequestParam("pageId") Integer pageId,
			@RequestParam("upload") MultipartFile file)
			throws MalformedURLException {
		Map<String, String> result = Maps.newHashMap();

		if (!file.isEmpty()) {
			try {
				byte[] bytes = file.getBytes();

				ImgPath imgPath = PathUtil.getImgPathInfo(request
						.getRequestURL().toString(), pageId);
				String imgFilePath = imgPath.getFullImgPath();
				File imgFile = new File(imgFilePath);
				File imgParentFile = imgFile.getParentFile();
				if (!imgParentFile.exists()) {
					imgParentFile.mkdirs();
				}

				BufferedOutputStream stream = new BufferedOutputStream(
						new FileOutputStream(imgFile));
				stream.write(bytes);
				stream.close();

				String url = imgPath.getImgBaseUrl() + pageId + "/"
						+ imgPath.getImgName() + ".png";
				result.put("url", url);
				result.put("fileName", imgPath.getImgName() + ".png");
				result.put("uploaded", "1");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return result;
	}
}